// pages/blueTooth.js
var app = getApp();
Page({
  data: {
     deviceId:0,
     services:0,
     writeId:0,
     inputValue:"ESP32-BLE",
     notifyId:0,
     consoleLog:"",
     userID:"wifi名称",
     userPassword:"wifi密码",
     VideoUrl:"https://profile-avatar.csdnimg.cn/35182f23fb704689bb4afa2cd4fc196d_qq_19707091.jpg!1",
     needReConnect:false,
     isconnect:false
  },
  onShow() {
    this.setData({
      VideoUrl:app.globalData.videoUrl
    })
  },
  inputPasword:function(options)
  {
    let pasw=options.detail.value
    console.log(pasw)
    this.setData({
      userPassword:pasw
    })
  },
  inputUserId:function(options)
  {
    let id=options.detail.value
    this.setData({
      userID:id
    })
  },
  //用户连接wifi才能使用
  getWifiMessage:function()
  {
    var that=this
    wx.startWifi({
      success(res) {
        console.log(res.errMsg, 'wifi初始化成功')
        wx.getConnectedWifi({
          success: function(e){
            console.log(e.wifi, 'wifi获取成功')
            console.log(e.wifi.SSID)
            that.setData({
              userID:e.wifi.SSID
            })
          },
          fail: function(e){
            console.log(e, 'wifi获取失败')
          }
        })
      },
      fail: function(res){
        console.log(res.errMsg, 'wifi初始化失败')
      }
    })
   
  },
  handle:function(){
    this.initBlue();
  },
  reConnect:function(){
    var that=this;
    console.log("10秒后重连")
   
    setTimeout(function(){
      wx.closeBluetoothAdapter({
        success: (res) => {
          console.log("已关闭蓝牙");
        },
        fail:(res)=>{
          console.log("蓝牙未能关闭");
        }
      })
      console.log("执行重连")
      that.setData({
        isconnect:false,
      })
      that.initBlue();
    },1000)
  },
  /**
   * 初始化蓝牙设备
   */
  initBlue:function(){
    var that = this;
    wx.openBluetoothAdapter({//调用微信小程序api 打开蓝牙适配器接口
      success: function (res) {
         
        wx.showToast({
          title: '初始化成功',
          icon: 'success',
          duration: 800
        })
        console.log("开始寻找设备")
        that.findBlue();//2.0
      },
      fail: function (res) {//如果手机上的蓝牙没有打开，可以提醒用户
        console.log(res)
        wx.showToast({
          title: '请开启蓝牙',
          icon: 'fails',
          duration: 1000
        })
      }
    })
  },
  /**
  *开始搜索蓝牙设备
*/
findBlue(){
  var that = this
  wx.startBluetoothDevicesDiscovery({
    allowDuplicatesKey: false,
    interval: 0,
    success: function (res) {
     
      // wx.showLoading({
      //   title: '正在搜索设备',
      // })
      that.getBlue()//3.0
    }
  })
},
/**
  * 获取搜索到的设备信息
 */
getBlue(){
  console.log("执行getblue")
  var that = this
  wx.getBluetoothDevices({
    success: function(res) {
     // wx.hideLoading();
      for (var i = 0; i < res.devices.length; i++){
　　　//that.data.inputValue：
　　　/**表示的是需要连接的蓝牙设备ID，简单点来说就是我想要连接这个蓝牙设备，
　　　所以我去遍历我搜索到的蓝牙设备中是否有这个ID
　　　*/
        console.log(res.devices[i].name)
        if (res.devices[i].name == that.data.inputValue || 
        res.devices[i].localName == that.data.inputValue){
          that.setData({
            deviceId: res.devices[i].deviceId,
            consoleLog: "设备：" + res.devices[i].deviceId,
            isconnect:true
          })
          console.log(res.devices[i].deviceId)
          that.connetBlue(res.devices[i].deviceId);//4.0
          return;
        }
      }
    },
    fail: function(){
      console.log("搜索蓝牙设备失败")
    },
    complete:function(){
      console.log(that.data.isconnect)
      if(that.data.isconnect==false)
      {
        setTimeout(() => {
          that.initBlue();
        },2000);
      }
    }
  })
},
/**
  * 获取到设备之后连接蓝牙设备
 */
connetBlue(deviceId){                    
  var that = this;
  wx.createBLEConnection({
    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
    deviceId: deviceId,//设备id
    fail:function(res){
      console.log(res)
    },
    success: function (res) {
      wx.showToast({
        title: '连接成功',
        icon: 'fails',
        duration: 800
      })
      console.log("连接蓝牙成功!")
      wx.setBLEMTU({
        deviceId: deviceId,
        mtu: 100,
      })
      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log('连接蓝牙成功之后关闭蓝牙搜索');
        }
      })
      that.getServiceId()//5.0
    }
  })
},
getServiceId(){
  var that = this
  wx.getBLEDeviceServices({
    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
    deviceId: that.data.deviceId,
    success: function (res) {
      var model = res.services[0]
      that.setData({
        services: model.uuid
      })
      console.log("执行getchara")
      that.getCharacteId()//6.0
    }
  })
},
getCharacteId(){
  var that = this 
  wx.getBLEDeviceCharacteristics({
    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
    deviceId: that.data.deviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: that.data.services,
    fail:function(res)
    {
      console.log(res)
      console.log(this.deviceId)
      console.log(this.serviceId)
    },
    success: function (res) {
      console.log(res)
      for (var i = 0; i < res.characteristics.length; i++) {//2个值
        var model = res.characteristics[i]
        console.log(model)
        if (model.properties.notify == true) {
          that.setData({
            notifyId: model.uuid//监听的值
          })
          console.log("执行startnotice")
          that.startNotice(model.uuid)//7.0
        }
        if (model.properties.write == true){
          console.log("执行write"+model.uuid)
          that.setData({
            writeId: model.uuid//用来写入的值
          })
          var nums={"0":that.data.userID,"1":that.data.userPassword}
          var json=JSON.stringify(nums)
          that.sendMy(that.string2buffer(json))
        }
      }
    }
  })
},
startNotice(uuid){
  var that = this;
  wx.notifyBLECharacteristicValueChange({
    state: true, // 启用 notify 功能
    // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接 
    deviceId: that.data.deviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: that.data.services,
    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
    characteristicId: uuid,  //第一步 开启监听 notityid  第二步发送指令 write
    success: function (res) {
    　　  // 设备返回的方法
          console.log("监听数据变化")
    　　  wx.onBLECharacteristicValueChange(function (res) {
              let dt=that.ab2hex(res.value)
              that.setData({
                VideoUrl:"https://i0.hdslb.com/bfs/face/2407e18f176b2e0d00b2035486fa7e19104a12c2.jpg@240w_240h_1c_1s_!web-avatar-space-header.avif"
              })
              app.globalData.videoUrl=dt
              if(dt!="请2秒后重新连接蓝牙")
              {
                wx.showLoading({
                  title: '等待设备连接',
                })
                setTimeout(() => {
                  wx.navigateTo({
                    url: '/pages/esp32/esp32',
                  })
                }, 15000);
              }
              else{
                that.reConnect();
              }
})
　　}
  })
},
sendMy(buffer){
  var that = this 
  wx.writeBLECharacteristicValue({
    // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取
    deviceId: that.data.deviceId,
    // 这里的 serviceId 需要在上面的 getBLEDeviceServices 接口中获取
    serviceId: that.data.services,
    // 这里的 characteristicId 需要在上面的 getBLEDeviceCharacteristics 接口中获取
    characteristicId: that.data.writeId,//第二步写入的特征值
    // 这里的value是ArrayBuffer类型
    value: buffer,
    success: function (res) {
      console.log("写入"+that.ab2hex(buffer))
      console.log("写入成功")
    },
    fail: function () {
      console.log('写入失败')
    },
    complete:function(){
      console.log("调用结束");
    }
  })
},
/**
* 将字符串转换成ArrayBufer
*/
string2buffer(str) {
  
  var bytes = new Array(); 
	var len,c;
	len = str.length;
	for(var i = 0; i < len; i++){
		c = str.charCodeAt(i);
		if(c >= 0x010000 && c <= 0x10FFFF){
			bytes.push(((c >> 18) & 0x07) | 0xF0);
			bytes.push(((c >> 12) & 0x3F) | 0x80);
			bytes.push(((c >> 6) & 0x3F) | 0x80);
			bytes.push((c & 0x3F) | 0x80);
		}else if(c >= 0x000800 && c <= 0x00FFFF){
			bytes.push(((c >> 12) & 0x0F) | 0xE0);
			bytes.push(((c >> 6) & 0x3F) | 0x80);
			bytes.push((c & 0x3F) | 0x80);
		}else if(c >= 0x000080 && c <= 0x0007FF){
			bytes.push(((c >> 6) & 0x1F) | 0xC0);
			bytes.push((c & 0x3F) | 0x80);
		}else{
			bytes.push(c & 0xFF);
		}
  }
  var array = new Int8Array(bytes.length);
  for(var i in bytes){
    array[i] =bytes[i];
  }
	return array.buffer;
},
 /**
   * 将ArrayBuffer转换成字符串
   */
  ab2hex(arrayBuffer) {
    let unit8Arr = new Uint8Array(arrayBuffer) ;
    let encodedString = String.fromCharCode.apply(null, unit8Arr),
    decodedString = decodeURIComponent(escape((encodedString)));//没有这一步中文会乱码
    console.log(decodedString);
    return decodedString
  },
})